package com.cgy.utils.elasticsearch.single;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;

/**
 * @author CH
 */
@Slf4j
public class ElasticSearchAdd {
    /**
     *
     * @param response
     * @return
     */
    public static boolean response(IndexResponse response) {
        String index = response.getIndex();
        String type = response.getType();
        String documentId = response.getId();
        if (response.getResult() == DocWriteResponse.Result.CREATED) {
            log.info("新增文档成功！ index: {}, type: {}, id: {}", index, type, documentId);
            return true;
        } else if (response.getResult() == DocWriteResponse.Result.UPDATED) {
            log.info("修改文档成功！ index: {}, type: {}, id: {}", index, type, documentId);
            return true;
        }
        // 分片处理信息
        ReplicationResponse.ShardInfo shardInfo = response.getShardInfo();
        if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
            log.error("文档未写入全部分片副本！");
            return true;
        }
        // 如果有分片副本失败，可以获得失败原因信息
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                String reason = failure.reason();
                log.error("副本失败原因：{}", reason);
            }
            return false;
        }
        return false;
    }
}
